package club.kynb.mall.application.flow.user;

import club.kynb.mall.application.context.AuthenticationContext;
import club.kynb.mall.application.model.model.command.AuthenticationCommand;
import club.kynb.mall.application.model.model.command.SmsFindPasswordCommand;
import club.kynb.mall.application.model.model.event.UserPwdUpdateEvent;
import club.kynb.mall.user.api.IUserService;
import club.kynb.mall.user.model.dto.UserDTO;
import cn.hutool.crypto.SecureUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pizza.common.web.exception.Errors;
import org.pizza.event.publish.EventBus;
import org.pizza.pattern.filter.Filter;
import org.pizza.pattern.filter.FilterInvoker;
import org.pizza.util.Checker;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author kynb_club@163.com
 * @since 2020/12/18 1:48 下午
 * 用户注册过滤器
 */
@Slf4j
@Component
@AllArgsConstructor
public class UserUpdatePwdFilter implements Filter<AuthenticationContext> {
    private final IUserService iUserService;
    private final EventBus eventBus;

    @Override
    public void doFilter(AuthenticationContext authenticationContext, FilterInvoker<AuthenticationContext> filterInvoker) {
        log.info("用户密码更新过滤器 start");
        AuthenticationCommand command = authenticationContext.getAuthenticationCommand();
        Checker.ifNotThrow(command instanceof SmsFindPasswordCommand
                , (b) -> log.error("流程配置有误，当前过滤器无法处理：{}", command.getClass().getSimpleName())
                , () -> Errors.BIZ.exception("流程配置有误，请联系开发者~"));
        SmsFindPasswordCommand smsFindPasswordCommand = (SmsFindPasswordCommand) command;
        final UserDTO user = authenticationContext.getUser();
        user.setSalt(UUID.randomUUID().toString());
        user.setPassword(SecureUtil.md5(smsFindPasswordCommand.getNewPassword() + user.getSalt()));
        iUserService.updateUser(user);
        eventBus.publishEvent(UserPwdUpdateEvent.builder()
                .userId(user.getId())
                .token(user.getCurrentToken())
                .build());
        log.info("用户密码更新过滤器 end");
        filterInvoker.invoke(authenticationContext);
    }
}
